import { _decorator, Collider, Component, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CAgent')
export class CAgent extends Component {
    // 代理的最大速度值
    // @property
    public maxSpeed: number = 5;
    // 代理的当前速度
    public velocity: Vec3 = new Vec3();

    // 代理的目标位置
    public target: Vec3 = new Vec3();

    @property
    public slowRadius: number = 200;
    // 代理的视野半径，用于检测障碍物和邻居
    @property
    public viewRadius: number = 10;

    // 代理的视野角度，用于检测障碍物和邻居
    @property
    public viewAngle: number = Math.PI / 2; // 90 degrees

    // 代理的邻居列表
    public neighbors: CAgent[] = [];

    // 代理的障碍物列表
    public obstacles: Collider[] = [];


    @property(Node)
    targetNode: Node = null;

    // Seek行为：朝着目标位置移动
    seek(target: Vec3, dt: number): Vec3 {
        let steering = new Vec3();
        let dis = Vec3.distance(this.node.position, target);
        if (dis < this.slowRadius) {
            let maxVelocity = target.subtract(this.node.position).normalize().multiplyScalar(this.maxSpeed);
            let desiredVelocity = maxVelocity.multiplyScalar(Math.min(1, dis / this.slowRadius));
            steering = desiredVelocity.subtract(this.velocity);
        }else{
            // 计算期望速度：从当前位置指向目标位置
            let desiredVelocity = target.subtract(this.node.position).normalize().multiplyScalar(this.maxSpeed);
            // 计算转向力：期望速度减去当前速度
            steering = desiredVelocity.subtract(this.velocity);
        }
        return steering;
    }

    // 障碍物回避行为
    obstacleAvoidance(dt: number): Vec3 {
        let avoidanceForce = new Vec3();
        // let closestObstacle: Collider = null;
        // let closestDistance = Infinity;

        // // 遍历所有障碍物
        // for (let obstacle of this.obstacles) {
        //     let direction = obstacle.node.position.clone().subtract(this.node.position);
        //     let distance = direction.length();

        //     // 检查障碍物是否在视野范围内
        //     if (distance < this.viewRadius && direction.angle(this.velocity) < this.viewAngle) {
        //         if (distance < closestDistance) {
        //             closestObstacle = obstacle;
        //             closestDistance = distance;
        //         }
        //     }
        // }

        // // 如果有障碍物在视野范围内，计算回避力
        // if (closestObstacle) {
        //     let avoidanceDirection = this.node.position.clone().subtract(closestObstacle.node.position).normalize();
        //     avoidanceForce = avoidanceDirection.multiplyScalar(this.maxSpeed);
        // }
        return avoidanceForce;
    }

    update(dt: number) {
        // 调用Seek行为并更新代理的位置
        let seekForce = this.seek(this.targetNode.getPosition(), dt);
        let pos = this.node.getPosition();
        this.node.position = pos.add(seekForce);
    }
}